package com.ruoyi.lvlian.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.ProductCategory;
import com.ruoyi.lvlian.dto.ProductCategoryDto;
import com.ruoyi.lvlian.dto.ProductDto;
import com.ruoyi.lvlian.mapper.ProductCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lvlian.mapper.ProductMapper;
import com.ruoyi.lvlian.domain.Product;
import com.ruoyi.lvlian.service.IProductService;

/**
 * 产品分类Service业务层处理
 *
 * @author lvlian
 * @date 2025-04-23
 */
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    /**
     * 查询产品分类
     *
     * @param id 产品分类主键
     * @return 产品分类
     */
    @Override
    public Product selectProductById(String id) {
        Product product= productMapper.selectProductById(id);
        return product;
    }

    /**
     * 查询产品分类列表
     *
     * @param product 产品分类
     * @return 产品分类
     */
    @Override
    public List<Product> selectProductList(ProductDto product) {
        return productMapper.selectProductList(product);
    }

    /**
     * 新增产品分类
     *
     * @param product 产品分类
     * @return 结果
     */
    @Override
    public int insertProduct(Product product) {

        product.setProductId(MD5Utils.md5(product.getName()));
        product.setId(MD5Utils.md5(product.getName()));
        product.setCreateUser(SecurityUtils.getUsername());
        product.setCreateDate(DateUtils.getCurrentTime());
        return productMapper.insertProduct(product);
    }

    /**
     * 修改产品分类
     *
     * @param product 产品分类
     * @return 结果
     */
    @Override
    public int updateProduct(Product product) {
        if (null == product.getCode() || 5 > product.getCode().length()) {
            product.setCode(Seq.getId());
        }

        int updateResult = 0;
        if (StringUtils.isEmpty(product.getId())) {
            updateResult = insertProduct(product);
        }
        updateResult = productMapper.updateProduct(product);
        if (0 == updateResult) {
            updateResult = insertProduct(product);
        }


        return updateResult;
    }

    /**
     * 批量删除产品分类
     *
     * @param ids 需要删除的产品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(String[] ids) {
        return productMapper.deleteProductByIds(ids);
    }

    /**
     * 删除产品分类信息
     *
     * @param id 产品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductById(String id) {
        return productMapper.deleteProductById(id);
    }

    @Override
    public List<Product> queryProductListByCategoryTree(ProductDto productDto) {
        return productMapper.selectProductList(productDto);
    }

    @Override
    public List<ProductCategory> queryTreeAndProductList(ProductCategoryDto productCategory) {

        // 一次性查出所有分类数据
        List<ProductCategory> allCategories = productCategoryMapper.selectProductCategoryAndProductList(productCategory);

        // 找出 level = 1 的根节点
        List<ProductCategory> rootList = allCategories.stream()
                .filter(c -> "1".equals(c.getLevel()))
                .collect(Collectors.toList());

        // 构建子树结构
        for (ProductCategory root : rootList) {
           buildTree(root, allCategories);
        }

        return rootList;
    }

    private void buildTree(ProductCategory parent, List<ProductCategory> allCategories) {
        String nextLevel = String.valueOf(Integer.parseInt(parent.getLevel()) + 1);
        List<ProductCategory> children = findChildrenByParentIdAndLevel(parent.getId(), nextLevel, allCategories);
        parent.setChild(children);

        for (ProductCategory child : children) {
            buildTree(child, allCategories); // 递归设置子节点
        }
    }

    public List<ProductCategory> findChildrenByParentIdAndLevel(Long parentId, String level, List<ProductCategory> allCategories) {
        return allCategories.stream()
                .filter(c -> Objects.equals(c.getParentId(), parentId) && level.equals(c.getLevel()))
                .collect(Collectors.toList());
    }
}
